<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 2017/1/10
 * Time: 下午1:49
 */

namespace Home\Controller;


use Common\Controller\HomeController;
use Common\Model\CategoryModel;
use Common\Model\GoodsAttrModel;
use Common\Model\GoodsModel;
use Common\Model\TypeAttrModel;

class CategoryController extends HomeController
{
	protected $goodsModel;
	protected $cid;
	protected $cateData;
	protected $categoryModel;
	protected $goodsAttrMode;
	public function __init ()
	{
		$this->categoryModel = new CategoryModel();
		$this->goodsModel = new GoodsModel();
		$this->goodsAttrMode = new GoodsAttrModel();
		$this->cid        = I( 'get.cid' , 0 );
		//所有的栏目数据
		$this->cateData = $this->categoryModel->select();
	}

	public function lists ()
	{
		//===toDo===要做数据筛选
		//1.通过cid 获得所有的父级栏目

		$father = $this->getFather($this->cateData,$this->cid);
		//翻转数组为前台遍历做准备
		$father = array_reverse($father);
		$this->assign('father',$father);
		//获得当前栏目的子栏目
		$cids = $this->getSon($this->cateData,$this->cid);
		//将自己放入
		$cids[] = $this->cid;
		//根据栏目id 获得栏目下所有商品的gid
		$gids = $this->goodsModel->where("cid in (".implode(',',$cids).")")->getField('gid',true);
		//根据gids 去商品属性表中，拿到所有的商品属性
		$attr = $this->goodsAttrMode->where("gid in (".implode(',',$gids).")")->group('gtvalue')->select();
		//整理数据，将taid一样的，放在一起
		$tempAttr = [];
		foreach($attr as $k=>$v){
			$tempAttr[$v['taid']][] = $v;
		}
		//根据taid去 type_attr表拿到 属性名数据
		$finalAttr = [];
		foreach ($tempAttr as $k=>$v){
			$name = (new TypeAttrModel())->where("taid=$k")->getField('taname');
			$finalAttr[] = [
				'name'=>$name,
				'value'=>$v
			];
		}
//		p(count($finalAttr));
//		筛选参数  ：0_0_0_0_0
		$param = isset($_GET['param']) ? explode('_',$_GET['param']) : array_fill(0,count($finalAttr),0);
		$this->assign('param',$param);
//		m=> 51_0_0_0_0
//		s=> 34_0_0_0_0
//		p($param);

		foreach ($param as $k=>$v){
			if($v){
				$gtvalue = $this->goodsAttrMode->where("gtid=$v")->getField('gtvalue');
				$attrGids[] = $this->goodsAttrMode->where("gtvalue='$gtvalue'")->getField('gid',true);
			}
		}
		$finalGids = [];
		if($attrGids){
			foreach ($attrGids as $k=>$v){
				$finalGids = $attrGids[0];
				$finalGids = array_intersect($finalGids,$v);
			}
			$finalGids = array_intersect($finalGids,$gids);
		}else{
			$finalGids = $gids;
		}
//		p($gids);
//		p($attrGids);
//		p($finalGids);

		$goodsList = $this->goodsModel->where("gid in (".implode(',',$finalGids).")")->select();
//		p($goodsList);
		$this->assign('goodsList',$goodsList);

		$this->assign('finalAttr',$finalAttr);

		$this->display();
	}
	private function getFather($data,$cid){
		static $temp = [];
		foreach ($data as $k=>$v){
			if($v['cid'] == $cid){
				$temp[] = $v;
				$this->getFather($data,$v['pid']);
			}
		}
		return $temp;
	}
	private function getSon($data,$cid){
		static $temp = [];
		foreach ($data as $k=>$v){
			if($v['pid'] == $cid){
				$temp[] = $v['cid'];
				$this->getSon($data,$v['cid']);
			}
		}
		return $temp;
	}
}